<?php
/**
 * 微仓类
 * @author 志杨
 *
 */
class MicroShop
{
	var $db;
	var $config;
	
	/**
	 * 官方店member_id
	 */
	private $officialMemberId = 14441;
	
	/**
	 * 推荐开店/升级店 红包规则
	 * @var array
	 */
	private $bonusRuleOfRecomendingShop = array(
	    '1'=>array(
	        'direct'=>1000,//直接推荐人获得
	        'indirect'=>300,//间接推荐人获得
	    ),
	    '2'=>array(
	        'direct'=>150,//直接推荐人获得
	        'indirect'=>50,//间接推荐人获得
	    ),
	    '3'=>array(
	        'direct'=>0,//直接推荐人获得
	        'indirect'=>0,//间接推荐人获得
	    ),
	);
	
	/**
	 * 购买套餐开店
	 * @var array
	 */
	private $bonusRuleOfRecomendingShops = array(
	    '2'=>array(
	        'direct'=>30,//直接推荐人获得
	        'indirect'=>10,//间接推荐人获得
	    )
	);
	
	/**
	 * 产生订单 红包规则  
	 * @var unknown
	 */
	private $bonusRuleOfOrder = array(
	    '1'=>array(
	        'self'     =>0.2,//本店返利百分比
	        'direct'   =>0,//直接推荐人获得
	        'permit_day'=>7//订单完成多久后可领取红包，单位：天
	    ),
	    '2'=>array(
	        'self'     =>0.1,
	        'direct'   =>0,//直接推荐人获得
	        'permit_day'=>7//订单完成多久后可领取红包，单位：天
	    ),
	    '3'=>array(
	        'self'     =>0,
	        'direct'   =>0,//直接推荐人获得
	        'permit_day'=>7//订单完成多久后可领取红包，单位：天
	    ),
	);

	/**
	 * 所有活动的分红规则
	 * @var array
	 */
	private $bonusRuleOfAll = array(
			// 普通区
			0	=> array(
					'1'=>array(
							'self'     =>0.2,//本店返利百分比
							'direct'   =>0,//直接推荐人获得
							'permit_day'=>7//订单完成多久后可领取红包，单位：天
					),
					'2'=>array(
							'self'     =>0.1,
							'direct'   =>0,//直接推荐人获得
							'permit_day'=>7//订单完成多久后可领取红包，单位：天
					),
					'3'=>array(
							'self'     =>0,
							'direct'   =>0,//直接推荐人获得
							'permit_day'=>7//订单完成多久后可领取红包，单位：天
					)
			),
			// 全返
			1	=> array(
					'1'=>array(
							'self'     =>0.2,//本店返利百分比
							'direct'   =>0,//直接推荐人获得
							'permit_day'=>7//订单完成多久后可领取红包，单位：天
					),
					'2'=>array(
							'self'     =>0.1,
							'direct'   =>0,//直接推荐人获得
							'permit_day'=>7//订单完成多久后可领取红包，单位：天
					),
					'3'=>array(
							'self'     =>0,
							'direct'   =>0,//直接推荐人获得
							'permit_day'=>7//订单完成多久后可领取红包，单位：天
					),
			),
			// 普通区，全场满99全返
			2	=> array(
					'1'=>array(
							'self'     =>0.2,//本店返利百分比
							'direct'   =>0,//直接推荐人获得
							'permit_day'=>7//订单完成多久后可领取红包，单位：天
					),
					'2'=>array(
							'self'     =>0.1,
							'direct'   =>0,//直接推荐人获得
							'permit_day'=>7//订单完成多久后可领取红包，单位：天
					),
					'3'=>array(
							'self'     =>0,
							'direct'   =>0,//直接推荐人获得
							'permit_day'=>7//订单完成多久后可领取红包，单位：天
					),
			),
    	    3	=> array(
    	        '1'=>array(
    	            'self'     =>0.2,//本店返利百分比
    	            'direct'   =>0,//直接推荐人获得
    	            'permit_day'=>7//订单完成多久后可领取红包，单位：天
    	        ),
    	        '2'=>array(
    	            'self'     =>0.1,
    	            'direct'   =>0,//直接推荐人获得
    	            'permit_day'=>7//订单完成多久后可领取红包，单位：天
    	        ),
    	        '3'=>array(
    	            'self'     =>0,
    	            'direct'   =>0,//直接推荐人获得
    	            'permit_day'=>7//订单完成多久后可领取红包，单位：天
    	        )
    	    )
	);

	/**
	 * 全返分红
	 * @var array
	 */
	private $bonusRuleOfQuanfan = array(
			'1'=>array(
					'self'     =>0.05,//本店返利百分比
					'direct'   =>0,//直接推荐人获得
					'permit_day'=>7//订单完成多久后可领取红包，单位：天
			),
			'2'=>array(
					'self'     =>0.03,
					'direct'   =>0,//直接推荐人获得
					'permit_day'=>7//订单完成多久后可领取红包，单位：天
			),
			'3'=>array(
					'self'     =>0,
					'direct'   =>0,//直接推荐人获得
					'permit_day'=>7//订单完成多久后可领取红包，单位：天
			),
	);
	
	/**
	 * 月销售额累计 额外红包规则    冲单奖
	 * @var unknown
	 */
	private $bonusRuleOfMonthSales = array(
	    '2'=>array(//暂时只有红人馆才有冲单奖
	        array(
	            'min'  =>10000,
	            'max'  =>29999,
	            'rate' =>0.01
	        ),
	        array(
	            'min'  =>30000,
	            'max'  =>49999,
	            'rate' =>0.02
	        ),
	        array(
	            'min'  =>50000,
	            'max'  =>999999,
	            'rate' =>0.03
	        ),
	    )
	);
	
	/**
	 * 拓展红人馆 额外红包规则  团队奖  此功能已屏蔽
	 * @var unknown
	 */
	private $bonusRuleOfExpandShop = array(
	    '1'=>array(//暂时只有首席馆才有拓展奖
            'num'  =>5,//满5家就发
            'price'  =>500
	    )
	);
	
	private $bonusTypeName = array(
	    '1'=>'推广奖',
	    '2'=>'销售奖',
	    '3'=>'服务奖',
	    '4'=>'推广任务奖',
	    '5'=>'销售冲单奖',
	);
	
	/**
	 * 免费升级店铺所需推广店铺数
	 * @var array $ruleOfUpgradeShopFree
	 */
	private $ruleOfUpgradeShopFree = array(
	    '2'=>array(
	        'num' =>100//推广吃货数量，达到后可免费升级红人馆
	    )
	);
	
	function __construct()
	{
		global $db,$config;
		
		$this -> db     = & $db;
		$this-> config  = $config;
		
		//================初始化微店配置数据==========
		$oMidArr = $this->getShopConfig('OFFICIAL_MEMBER_ID');
		if(!empty($oMidArr)){
		    $this->officialMemberId = intval($oMidArr[0]['value']);//官方首席馆ID
		}
		
		$configArr = array(
		    'BONUS_RULE_REC_SHOP'=>'bonusRuleOfRecomendingShop',
		    'BONUS_RULE_ORDER'=>'bonusRuleOfOrder',
		    'BONUS_RULE_MONTH_SALES'=>'bonusRuleOfMonthSales',
		    'BONUS_RULE_EXPAND_SHOP'=>'bonusRuleOfExpandShop',
		    'UPGRADE_SHOP_FREE'=>'ruleOfUpgradeShopFree',
		);
		foreach ($configArr as $k=>$v)
		{
		    $configValue = $this->getShopConfig($k,true);
		    if(!empty($configValue)){
    		    $this->$v = $configValue;
		    }
		}
		//=========================================
	}
	
	/**
	 * 获取某用户下一级微店信息
	 * @param int $memberId 默认取顶级合伙人信息
	 * @param boolean $isSelf 是否只查当前用户（用户ID大于0有效）
	 */
	function get_tarento_list($memberId=0,$isSelf=FALSE){
	    $res = array();
	    $sql = "";
	    if($memberId==0){//查顶级合伙人列表
	        $sql = "select a.*,b.name,b.qq,b.weixin,b.mobile,c.name as shop_name,c.personal_qrcode,IFNULL((SELECT d.name from haiou_micro_shop d where d.member_id=a.direct_rec_mid),'') as direct_shop_name,IFNULL((SELECT e.name from haiou_micro_shop e where e.member_id=a.indirect_rec_mid),'') as indirect_shop_name from ".TARENTO." AS a left join ".MEMBER." AS b ON a.member_id=b.userid left join ".MICROSHOP." AS c on a.member_id=c.member_id where a.level=1 and a.relations!='' and c.status>0 order by a.level,c.create_time";
	    }elseif ($memberId>0){
	        if($isSelf){//只查当前传入用户信息
	            $sql = "select a.*,b.name,b.qq,b.weixin,b.mobile,c.name as shop_name,c.personal_qrcode,IFNULL((SELECT d.name from haiou_micro_shop d where d.member_id=a.direct_rec_mid),'') as direct_shop_name,IFNULL((SELECT e.name from haiou_micro_shop e where e.member_id=a.indirect_rec_mid),'')  as indirect_shop_name from ".TARENTO." AS a left join ".MEMBER." AS b ON a.member_id=b.userid left join ".MICROSHOP." AS c on a.member_id=c.member_id where a.member_id={$memberId} and c.status>0";
	        }else{//查当前传入用户直系下一级合伙人列表
	            //先通过当前用户信息得到下一级查询条件
	            $sqlTemp = "select relations,level from ".TARENTO." where member_id={$memberId}";
	            $this->db->query($sqlTemp);
	            $memberInfo = $this->db->fetchRow();
	            if(!empty($memberInfo)){
	                $countR = substr_count($memberInfo['relations'], ',');
	                $condStr = " a.relations like '".$memberInfo['relations']."_%' and (LENGTH(relations) - LENGTH(REPLACE(relations,',',''))) = ".($countR+1);
	                $sql = "select a.*,b.name,b.qq,b.weixin,b.mobile,c.name as shop_name,c.personal_qrcode,IFNULL((SELECT d.name from haiou_micro_shop d where d.member_id=a.direct_rec_mid),'') as direct_shop_name,IFNULL((SELECT e.name from haiou_micro_shop e where e.member_id=a.indirect_rec_mid),'') as indirect_shop_name from ".TARENTO." AS a left join ".MEMBER." AS b ON a.member_id=b.userid left join ".MICROSHOP." AS c on a.member_id=c.member_id where {$condStr} and c.status>0 order by a.level,c.create_time";
	                
	                $this->db->query($sql);
	                $res = $this->db->getRows();
	                
	                return $res;
	            }
	        }
	    }
	    if(!empty($sql)){
	        $this->db->query($sql);
	        $res = $this->db->getRows();
	    }
	
	    return $res;
	}
	
	/**
	 * 获取微店用户详细信息
	 * @param unknown $memberId
	 */
	function get_tarento_detail($memberId){
	    $res = array();
	    if($memberId){
	        $sql = "select a.*,b.name,b.qq,b.weixin,b.mobile from ".TARENTO." AS a left join ".MEMBER." AS b ON a.member_id=b.userid where a.member_id={$memberId}";
	        $this->db->query($sql);
	        $res = $this->db->fetchRow();
	        if(!empty($res)){
	            //团队人数
	            $res['member_num'] = $this->get_tarento_group_total_num($memberId);
	            //商圈人数
	            $res['business_num'] = $this->get_tarento_business_total_num($memberId);
	            //获取合伙人及他的团队本月销售额
	            $sales = $this->get_tarento_current_month_sales($memberId);
	            $res = array_merge($res,$sales);
	        }
	    }
	
	    return $res;
	}
	
	/**
	 * 获取某微店团队总人数（包含他自己）
	 * @param unknown $memberId
	 */
	function get_tarento_group_total_num($memberId){
	    $num = 0;
	    if($memberId>0){
	        $sqlTemp = "select relations,level from ".TARENTO." where member_id={$memberId}";
	        $this->db->query($sqlTemp);
	        $memberInfo = $this->db->fetchRow();
	        if(!empty($memberInfo) && $memberInfo['relations']!=''){
	            $sql = "select count(*) as num from ".TARENTO." a left join ".MICROSHOP." b on a.member_id=b.member_id where a.relations like '".$memberInfo['relations']."_%' and b.status>0 ";
	            $this->db->query($sql);
	            $num = $this->db->fetchField('num');
	        }
	    }
	    return $num;
	}
	
	/**
	 * 获取合商圈总人数（包含他自己）
	 * @param unknown $memberId
	 */
	function get_tarento_business_total_num($memberId){
	    $num = 0;
	    if($memberId>0){
	        $sqlTemp = "select relations,level from ".TARENTO." where member_id={$memberId}";
	        $this->db->query($sqlTemp);
	        $memberInfo = $this->db->fetchRow();
	        if(!empty($memberInfo) && $memberInfo['relations']!=''){
	            $sql = "select count(*) as num from ".TARENTO." where relations like '".$memberInfo['relations']."_%' ";
	            $this->db->query($sql);
	            $num += $this->db->fetchField('num');
	        }
	    }
	
	    return $num;
	}
	
	/**
	 * 获取某微店及他的团队本月销售额
	 * @param unknown $memberId
	 * @param unknown $monthStr 如201509
	 */
	function get_tarento_current_month_sales($memberId,$monthStr=''){
	    $selfSales = 0;
	    $teamSales = 0;
	    if(empty($monthStr)){
	        $monthStr = date('Ym');
	    }
	    $sql = "select self_sales,group_sales from ".MICROSHOPSALESFLOW." where member_id={$memberId} and flow_time_str='{$monthStr}'";
	    $this->db->query($sql);
	    $memberInfo = $this->db->fetchRow();
	    $selfSales = $memberInfo['self_sales']?$memberInfo['self_sales']:0;
	    $teamSales = $memberInfo['group_sales']?$memberInfo['group_sales']:0;

	    return array('self_sales'=>$selfSales,'group_sales'=>$teamSales);
	}
	
	/**
	 * 获取用户店铺信息
	 * @param unknown $memberId
	 */
	public function get_shop_info($memberId) {
	    $res = array();
	    $sql = "select * from ".MICROSHOP." where member_id={$memberId}";
	    $this->db->query($sql);
	    $res = $this->db->fetchRow();
	    return $res;
	}
	
	/**
	 * 获取用户返利结算记录信息
	 * @param unknown $memberId
	 */
	function get_tarento_rebate_records($memberId){
	    $arr = array();
	    if($memberId>0){
	        $sql = "select * from ".MICROSHOPSALESFLOW." where member_id={$memberId} ";
	        $this->db->query($sql);
	        $arr = $this->db->getRows();
	        if(!empty($arr)){
	            foreach ($arr as $k=>$v)
	            {
	                $arr[$k]['formart_time'] = substr($v['flow_time_str'], 0, 4)."年".substr($v['flow_time_str'], 4)."月";
	            }
	        }
	    }
	    return $arr;
	}
	
	/**
	 * 开店
	 * @param unknown $memberId
	 * @param array $shopInfo
	 * @param unknown $payInfo 支付信息
	 */
	public function create_shop($memberId,$shopData = array(),$payInfo = array(),$level=null){
	    if($memberId>0){
	        //检查有无组织关系,无则绑定到官方店下面
            $sql = "select relations,invite_code from ".TARENTO." where member_id={$memberId}";
            $this->db->query($sql);
            $mInfo = $this->db->fetchRow();
            $relations = '';
            $code = '';
            if(!empty($mInfo)){
                $relations = $mInfo['relations'];
                $code = $mInfo['invite_code'];
            }
            if(empty($relations)){
                $sql = "update ".TARENTO." set relations='{$this->officialMemberId},{$memberId},',level=3,direct_rec_mid={$this->officialMemberId} where member_id={$memberId}";
                $this->db->query($sql);
            }
            if(empty($code) && $level == 1){
                include_once($this->config["webroot"]."/module/product/includes/plugin_tarento_class.php");
                $tarento = new Tarento();
                $code = $tarento->buildInviteCode($memberId);//邀请码
                $sql = "update ".TARENTO." set invite_code='{$code}' where member_id={$memberId}";
                $this->db->query($sql);
            }
	        
	        $sql = "select level,status from ".MICROSHOP." where member_id={$memberId}";
	        $this->db->query($sql);
	        $shopInfo = $this->db->fetchRow();
	        
	        if(empty($shopInfo)){//后台操作
	            $shopName      = "";//店铺名称
	            $userName      = "";//真实姓名
	            $userIdCard    = "";//身份证号
	            if(!empty($shopData)){
	                $shopName      = $shopData['shopName'];
	                $userName      = $shopData['userName'];
                    $userIdCard    = $shopData['userIdCard'];
	            }
	            $sql = "insert into ".MICROSHOP." (`member_id`,`name`,`user_real_name`,`user_idcard`,`level`,`status`) value('{$memberId}','{$shopName}','{$userName}','{$userIdCard}',3,1)";
	            $this->db->query($sql);
	        }else{//前台操作
	            if($shopInfo['status']==1){
	                return false;
	            }
	            $nowTime = date('Y-m-d H:i:s');
	            $sql = "update ".MICROSHOP." set `status`=1,`create_time`='{$nowTime}' where member_id={$memberId}";
	            $this->db->query($sql);
	        }
	        
	        //更新tarento表中 是否开店为1
	        $sql = "update ".TARENTO." set `have_micro_shop`=1 where member_id={$memberId}";
	        $this->db->query($sql);
	        
	        //更新树结构
	        $this->change_tarento_tree($memberId, 3);
	        
	        //开店成功后允许升级
	        $sql = "update ".TARENTO." set can_upgrade_shop=1 where member_id={$memberId}";
	        $this->db->query($sql);
	        
	        //写入支付日志
	        $payInfo['member_id'] = $memberId;
	        $this->insertOnePayLog($payInfo);
	        
	        return true;
	    }
	    
	    return false;
	}
	
	/**
	 * 店铺升级
	 * @param unknown $memberId
	 * @param unknown $level 升级到什么级别
	 * @param unknown $payInfo 支付信息
	 */
	public function upgrade_shop($memberId,$level,$orderId=null,$payInfo = array(),$type = null){
	    if($memberId>0){
	        $sql = "select level from ".MICROSHOP." where member_id={$memberId}";
	        $this->db->query($sql);
	        $shopInfo = $this->db->fetchRow();
	        
	        //查询店铺是否可升级
	        $sql = "select can_upgrade_shop,invite_code from ".TARENTO." where member_id={$memberId}";
	        $this->db->query($sql);
	        $canUpgrade = $this->db->fetchRow();
// 	        $canUpgrade = $this->db->fetchField('can_upgrade_shop');
// 	        $invite_code = $this->db->fetchField('invite_code');
	        
	        if(empty($canUpgrade['invite_code']) && $level == 1){
	            include_once($this->config["webroot"]."/module/product/includes/plugin_tarento_class.php");
	            $tarento = new Tarento();
	            $code = $tarento->buildInviteCode($memberId);//邀请码
	            $sql = "update ".TARENTO." set invite_code='{$code}' where member_id={$memberId}";
	            $this->db->query($sql);
	        }
	        
	        if(!empty($shopInfo) && $canUpgrade['can_upgrade_shop'] == 1){
	            if($shopInfo['level']>$level){
    	            //更新店铺等级
    	            $sql = "update ".MICROSHOP." set level={$level} where member_id={$memberId}";
                    $this->db->query($sql);
                    
                    //更新树层级结构
                    $status = $this->change_tarento_tree($memberId, $level);
                    
                    if(empty($type) || $type == null){
                        //返红包
                        $this->giveOutBonusOfRecShop($memberId,$orderId);
                        //返红包
//                         $sql = "select have_discount_price from ".TARENTO." where member_id={$memberId}";
//                         $this->db->query($sql);
//                         $have_discount_price = $this->db->fetchField('have_discount_price');
                        
//                         //获取是否需要返红包
//                         $needStatus = $this->canOrNotGiveBonusAndCoupons($level, $have_discount_price);
//                         if($status && $needStatus){//改变树结构成功并且允许返则返红包
//                             $this->giveOutBonusOfRecShop($memberId);
//                         }
                    }
                        
                    
                    //写入支付日志
                    $payInfo['member_id'] = $memberId;
                    $this->insertOnePayLog($payInfo);
                    
                    return true;
	            }
	            return false;
	        }
	        
	        return false;
	    }
	    
	    return false;
	}
	
	/**
	 * 改变树结构
	 * @param unknown $memberId
	 * @param unknown $level
	 */
	public function change_tarento_tree($memberId,$level){
	    $sql = "select direct_rec_mid,indirect_rec_mid,relations,level,have_discount_price from ".TARENTO." where member_id={$memberId}";
	    $this->db->query($sql);
	    $memInfo = $this->db->fetchRow();
	    if(!empty($memInfo)){
	        if($memInfo['level']==1){//已经是首席馆不改变
	            return false;
	        }
	        if($memInfo['level']>=$level){
	            $shopLevel = "";
	            $resStatus = false;
                $relationsPre = str_replace(','.$memberId.',', '', $memInfo['relations']).",";//升级之前 上一级的relations
                $recMemInfo = $this->getMemberRecMemInfo($memberId,$memInfo, $level);
    	        switch ($level)
    	        {
    	            case 1://升级为首席馆
    	                $shopLevel = "首席馆";
    	                //更新该用户
    	                $sql = "update ".TARENTO." set direct_rec_mid='{$recMemInfo['direct_rec_mid']}',indirect_rec_mid='{$recMemInfo['indirect_rec_mid']}',relations='{$recMemInfo['relations']}',level=1 where member_id={$memberId}";
    	                $this->db->query($sql);
    	                
    	                //更新该用户下级的relations和level
//     	                $num = $memInfo['level']-2;//计算下级level的系数
    	                $sql = "update ".TARENTO." set relations=REPLACE(relations,'{$relationsPre}','') where relations like '".$memInfo['relations']."_%'";
    	                $this->db->query($sql);
    	                
    	                //更新该用户下级的间接推荐人
    	                $sql = "update ".TARENTO." set indirect_rec_mid='{$recMemInfo['direct_rec_mid']}' where relations like '".$memInfo['relations']."_%' and level=3";
    	                $this->db->query($sql);//更新直接下一级
    	                
    	                if($memInfo['level']==2){//如果升级之前是红人馆，则与他推广的红人馆断开推荐关系
    	                    $sql = "select member_id,relations from ".TARENTO." where direct_rec_mid={$memberId} and level=2";
    	                    $this->db->query($sql);
    	                    $expandShops = $this->db->getRows();
    	                    if(!empty($expandShops)){
    	                        foreach ($expandShops as $exv)
    	                        {
    	                            $fMid = strstr($exv['relations'], ',', true);//顶级首席馆ID
    	                            if($fMid>0){
    	                                $sql = "select direct_rec_mid from ".TARENTO." where member_id={$fMid}";
    	                                $this->db->query($sql);
    	                                $fdrmid = $this->db->fetchField('direct_rec_mid');//首席馆的直接推荐人
    	                                
    	                                //更新
    	                                $sql = "update ".TARENTO." set direct_rec_mid='{$fMid}',indirect_rec_mid='{$fdrmid}' where member_id={$exv['member_id']}";
    	                                $this->db->query($sql);
    	                            }
    	                        }
    	                    }
    	                }
    	                
    	                //=========发优惠券=========
    	                //获取是否需要返红包   发放优惠券
//     	                $needStatus = $this->canOrNotGiveBonusAndCoupons($level, $memInfo['have_discount_price']);
//     	                if($needStatus){
//         	                include_once($this->config["webroot"]."/module/micro_shop/includes/plugin_coupons_class.php");
//         	                $couponsObj = new Coupons();
//         	                $couponsObj->createOnePackage($memberId, 1);    //发放优惠券
//     	                }
    	                //=======================
    	                
    	                $resStatus = true;
    	                
    	                //给店主推送消息
    	                $replaceArr = [
    	                    'subject'=>[
    	                        '{{shopLevel}}'=>$shopLevel
    	                    ]
    	                ];
    	                
    	                $sql = "select name from ".MICROSHOP." where member_id={$memberId} limit 1";
    	                $this->db->query($sql);
    	                $shopName = $this->db->fetchField('name');
    	                $param = [
    	                    'memberId'=>$memberId,
    	                    'keyword1'=>$shopName,
    	                    'keyword2'=>date('Y-m-d H:i:s'),
    	                    'url'     =>'http://wx.52ywy.com'
    	                ];
    	                include_once($this->config["webroot"]."/lib/Helper.php");
    	                Helper::pushMessage('shopUpgradeSuccess', $replaceArr, $param);
    	                
    	                break;
    	            case 2://升级为红人馆
    	                $shopLevel = "红人馆";
    	                //更新该用户
    	                $sql = "update ".TARENTO." set direct_rec_mid='{$recMemInfo['direct_rec_mid']}',indirect_rec_mid='{$recMemInfo['indirect_rec_mid']}',relations='{$recMemInfo['relations']}',level=2 where member_id={$memberId}";
    	                $this->db->query($sql);
    	                
    	                //更新该用户下级的relations和level
//     	                $num = $memInfo['level']-2;//计算下级level的系数
    	                $fMid = strstr($relationsPre, ',', true);//顶级首席馆ID
    	                $sql = "update ".TARENTO." set relations=REPLACE(relations,'{$relationsPre}','{$fMid},') where relations like '".$memInfo['relations']."_%'";
    	                $this->db->query($sql);
    	                
    	                //更新该用户下级的间接推荐人
    	                $sql = "update ".TARENTO." set indirect_rec_mid='{$recMemInfo['direct_rec_mid']}' where relations like '".$memInfo['relations']."_%' and level=3";
    	                $this->db->query($sql);//更新直接下一级
    	                
//     	                //检查上级首席馆下有多少红人馆（发拓展红包）
//     	                $sql = "select count(*) as totalNum from ".TARENTO." where relations like '".$fMid.",_%' and level=2";
//     	                $this->db->query($sql);
//     	                $totalNum = $this->db->fetchField('totalNum');
//     	                if($totalNum>0 && $this->bonusRuleOfExpandShop['1']['num']>0){
//     	                    if(($totalNum % $this->bonusRuleOfExpandShop['1']['num'])==0){
//     	                        $data = array(
//     	                            'member_id'     =>$fMid,
//     	                            'type'          =>4,
//     	                            'price'         =>$this->bonusRuleOfExpandShop['1']['price'],
//     	                            'p_settle_time' =>date('Y-m-d H:i:s'),
//     	                            'releranceInfo'  =>array(
//     	                                'rec_member_id'     =>$fMid,
//     	                                'expand_shop_number'=>$this->bonusRuleOfExpandShop['1']['num']
//     	                            )
//     	                        );
//     	                        $this->insertOneBonusDetail($data,'task_expand');
//     	                    }
//     	                }
    	                
    	                //================发优惠券=============
    	                //获取是否需要返红包
//     	                $needStatus = $this->canOrNotGiveBonusAndCoupons($level, $memInfo['have_discount_price']);
//     	                if($needStatus){
//         	                include_once($this->config["webroot"]."/module/micro_shop/includes/plugin_coupons_class.php");
//         	                $couponsObj = new Coupons();
//         	                $couponsObj->createOnePackage($memberId, 2);
//     	                }
    	                //=========================
    	                
    	                $resStatus = true;
    	                
    	                //给店主推送消息
    	                $replaceArr = [
    	                    'subject'=>[
    	                        '{{shopLevel}}'=>$shopLevel
    	                    ]
    	                ];
    	                
    	                $sql = "select name from ".MICROSHOP." where member_id={$memberId} limit 1";
    	                $this->db->query($sql);
    	                $shopName = $this->db->fetchField('name');
    	                $param = [
    	                    'memberId'=>$memberId,
    	                    'keyword1'=>$shopName,
    	                    'keyword2'=>date('Y-m-d H:i:s'),
    	                    'url'     =>'http://wx.52ywy.com'
    	                ];
    	                include_once($this->config["webroot"]."/lib/Helper.php");
    	                Helper::pushMessage('shopUpgradeSuccess', $replaceArr, $param);
    	                
    	                break;
    	            case 3://开店
    	                $shopLevel = "吃货";
    	                $sql = "select `level` from ".TARENTO." where member_id={$recMemInfo['direct_rec_mid']}";
    	                $this->db->query($sql);
    	                $levelTemp = $this->db->fetchField('level');
    	                //更新该用户
    	                $sql = "update ".TARENTO." set direct_rec_mid='{$recMemInfo['direct_rec_mid']}',indirect_rec_mid='{$recMemInfo['indirect_rec_mid']}',relations='{$recMemInfo['relations']}',level= 3 where member_id={$memberId}";
    	                $this->db->query($sql);
    	                
    	                //更新该用户下级的relations
    	                $sql = "update ".TARENTO." set relations=REPLACE(relations,'{$memInfo['relations']}','{$recMemInfo['relations']}') where relations like '".$memInfo['relations']."_%'";
    	                $this->db->query($sql);
    	                
    	                //更新该用户下级的间接推荐人
    	                $sql = "update ".TARENTO." set indirect_rec_mid='{$recMemInfo['direct_rec_mid']}' where relations like '".$recMemInfo['relations']."_%' ";
    	                $this->db->query($sql);//更新直接下一级
    	                
    	                //查询上级是否为吃货，是则统计上级吃货直接推广的吃货数量（获得免费升级红人馆资格）
    	                $bossIdStr = ','.str_replace(','.$memberId.',', '', $memInfo['relations']);
    	                $bossMid = substr($bossIdStr, strrpos($bossIdStr,','));//上级店铺ID
    	                $bossMid = trim($bossMid,',');
    	                if($bossMid>0){
        	                $sql = "select * from ".TARENTO." where member_id={$bossMid}";
        	                $this->db->query($sql);
        	                $bossInfo = $this->db->fetchRow();
        	                if(!empty($bossInfo) && $bossInfo['level']>=3 && $bossInfo['have_discount_price']!=3){
        	                    $sql = "select count(*) as shopNum from ".TARENTO." where relations like '".$bossInfo['relations']."_%' and level={$bossInfo['level']}+1 and have_micro_shop=1";
        	                    $this->db->query($sql);
        	                    $shopNum = $this->db->fetchField('shopNum');
        	                    if($shopNum == $this->ruleOfUpgradeShopFree['2']['num']){//获得免费升级红人馆资格
        	                        $sql = "update ".TARENTO." set have_discount_price=3 where member_id={$bossMid}";
        	                        $this->db->query($sql);
        	                    }
        	                }
    	                }
    	                
    	                //发红包
//     	                $this->giveOutBonusOfRecShop($memberId);
    	                
    	                //================发优惠券=============
    	                //获取是否需要返红包   发放优惠券
//     	                $needStatus = $this->canOrNotGiveBonusAndCoupons($level, $memInfo['have_discount_price']);
//     	                if($needStatus){
//     	                    include_once($this->config["webroot"]."/module/micro_shop/includes/plugin_coupons_class.php");
//     	                    $couponsObj = new Coupons();
//     	                    $couponsObj->createOnePackage($memberId, 3);
//     	                }
    	                //=========================
    	                
    	                $resStatus = true;
    	                
    	                //给店主推送消息
    	                $replaceArr = [];
    	                 
    	                $sql = "select name from ".MICROSHOP." where member_id={$memberId} limit 1";
    	                $this->db->query($sql);
    	                $shopName = $this->db->fetchField('name');
    	                $param = [
    	                    'memberId'=>$memberId,
    	                    'keyword1'=>$shopName,
    	                    'keyword2'=>date('Y-m-d H:i:s'),
    	                    'url'     =>'http://wx.52ywy.com'
    	                ];
    	                include_once($this->config["webroot"]."/lib/Helper.php");
    	                Helper::pushMessage('openShopSuccessSelf', $replaceArr, $param);
    	                
    	                break;
	                default:
	                    break;
    	        }
    	        
    	        //给上级店主推送消息
    	        $replaceArr = [
    	            'subject'=>[
    	                '{{shopLevel}}'=>$shopLevel
    	            ]
    	        ];
    	        $sql = "select direct_rec_mid from ".TARENTO." where member_id={$memberId}";
    	        $this->db->query($sql);
    	        $memNewInfo = $this->db->fetchRow();
    	        $sql = "select name from ".MICROSHOP." where member_id={$memberId} limit 1";
    	        $this->db->query($sql);
    	        $shopName = $this->db->fetchField('name');
    	        $param = [
    	            'memberId'=>$memNewInfo['direct_rec_mid'],
    	            'keyword1'=>$shopName,
    	            'keyword2'=>date('Y-m-d H:i:s'),
    	            'url'     =>'http://wx.52ywy.com/?shop='.$memNewInfo['direct_rec_mid'].'#&shop/fendian'
    	        ];
    	        include_once($this->config["webroot"]."/lib/Helper.php");
    	        Helper::pushMessage('openShopSuccess', $replaceArr, $param);
    	        
    	        return $resStatus;
	        }
	    }
	    return false;
	}
	
	/**
	 * 获取升级后直接推荐人和间接推荐人ID和relations
	 * @param unknown $meberInfo
	 * @param unknown $level
	 */
	private function getMemberRecMemInfo($memberId,$meberInfo,$level){
	    $dmid = 0;//直接推荐人ID
	    $indmid = 0;//间接推荐人ID
	    $relations = '';
	    if(!empty($meberInfo)){
	        if($meberInfo['direct_rec_mid']>0 && $meberInfo['direct_rec_mid']!=$this->officialMemberId){
	            $sql = "select direct_rec_mid,indirect_rec_mid,level from ".TARENTO." where member_id={$meberInfo['direct_rec_mid']}";
	            $this->db->query($sql);
	            $directMemInfo = $this->db->fetchRow();
	            $directMemlevel = $directMemInfo['level'];
	            
	            switch ($level){
	                case 1:
	                    if($directMemlevel==1){
	                        $dmid = $meberInfo['direct_rec_mid'];
	                        $indmid = $directMemInfo['direct_rec_mid'];
                        }else{
                            $dmid = strstr($meberInfo['relations'],',',true);
                            $sql = "select direct_rec_mid from ".TARENTO." where member_id={$dmid}";
                            $this->db->query($sql);
                            $indmid = $this->db->fetchField('direct_rec_mid');
	                    }
	                    
	                    $relations = $memberId.",";
	                    break;
	                case 2:
	                    if($directMemlevel==1){
	                        $dmid = $meberInfo['direct_rec_mid'];
	                        $indmid = $directMemInfo['direct_rec_mid'];
	                        $relations = $meberInfo['direct_rec_mid'].",".$memberId.",";
	                    }elseif($directMemlevel==2){
	                        $fMid = strstr($meberInfo['relations'],',',true);//顶级首席馆的ID
	                        
	                        $dmid = $meberInfo['direct_rec_mid'];
	                        $indmid = $directMemInfo['direct_rec_mid'];
	                        $relations = $fMid.",".$memberId.",";
	                    }else{
	                        $fMid = strstr($meberInfo['relations'],',',true);//顶级首席馆的ID
	                        $tempRelations = str_replace(','.$fMid.',', '', ','.$meberInfo['relations']);
	                        $sMid = strstr($tempRelations,',',true);//第二级店的ID
	                        
	                        $sql = "select direct_rec_mid,level from ".TARENTO." where member_id={$sMid}";
	                        $this->db->query($sql);
	                        $sMInfo = $this->db->fetchRow();
	                        if($sMInfo['level']==2){
	                            $dmid = $sMid;
	                            $indmid = $sMInfo['direct_rec_mid'];
	                        }else{
	                            $dmid = $fMid;
	                            $sql = "select direct_rec_mid from ".TARENTO." where member_id={$dmid}";
	                            $this->db->query($sql);
	                            $indmid = $this->db->fetchField('direct_rec_mid');
	                        }
	                        
                            $relations = $fMid.",".$memberId.",";
	                    }
	                    break;
	                case 3://开店
	                    if($directMemlevel>=3){
	                        $sql = "select member_id from ".MICROSHOP." where member_id={$meberInfo['direct_rec_mid']}";
	                        $this->db->query($sql);
	                        $directShopInfo = $this->db->fetchRow();
	                        if(empty($directShopInfo)){//直接推荐人没开店
	                            //把树上所有人的开店情况查出来
	                            $memIds = str_replace(','.$memberId.',', '', $meberInfo['relations']);
	                            $memIdArr = explode(',', $memIds);
	                            $sql = "select member_id,`level` from ".MICROSHOP." where member_id in({$memIds})";
	                            $this->db->query($sql);
	                            $memTemp = $this->db->getRows();
	                            $memArr = array();
	                            foreach ($memTemp as $val)
	                            {
	                                $memArr[$val['member_id']] = $val['level'];
	                            }
	                            $relationsTemp = "";
	                            $preMemId = 0;
	                            foreach ($memIdArr as $mid)
	                            {
	                                if(empty($memArr[$mid])){
	                                    break;
	                                }
	                                
	                                $preMemId = $mid;
	                                $relationsTemp .= $mid.",";
	                            }
	                            
	                            $dmid = $preMemId;
	                            $sql = "select direct_rec_mid from ".TARENTO." where member_id={$dmid}";
	                            $this->db->query($sql);
	                            $indmid = $this->db->fetchField('direct_rec_mid');
	                            $relations = $relationsTemp.$memberId.",";
	                        }else{
	                            $dmid = $meberInfo['direct_rec_mid'];
	                            $indmid = $meberInfo['indirect_rec_mid'];
	                            $relations = $meberInfo['relations'];
	                        }
	                    }else{
	                        $dmid = $meberInfo['direct_rec_mid'];
	                        $indmid = $meberInfo['indirect_rec_mid'];
	                        $relations = $meberInfo['relations'];
	                    }
	                    break;
                    default:
                        $dmid = $meberInfo['direct_rec_mid'];
	                    $indmid = $meberInfo['indirect_rec_mid'];
                        break;
	            }
	        }else{
	            $dmid = $this->officialMemberId;
	            if($level==1){
	                $relations = $memberId.",";
	            }else{
	                $relations = $this->officialMemberId.",".$memberId.",";
	            }
	        }
	    }
	    
	    return array('direct_rec_mid'=>$dmid,'indirect_rec_mid'=>$indmid,'relations'=>$relations);
	}
	
	/**
	 * 给推荐人发红包    -- 直接支付298
	 * @param unknown $memberId 开店或升级店铺的用户ID
	 */
	public function giveOutBonusOfRecShop($memberId,$orderId=null){
	    if($memberId>0){
            $sql = "select level from ".MICROSHOP." where member_id={$memberId}";
            $this->db->query($sql);
            $level = $this->db->fetchField('level');
            if($level > 0 && $level < 3){     //只有红人馆店和首席馆才有推广奖
                $allCost = '';
                $product_id = '';
                if($orderId){
                    //查询当前购买产品ID
            	    $sql = "select product_id,active_id from ".ORPRO." where order_id = '".$orderId."'";
            		$this->db->query($sql);
            		$ret_order_product = $this->db->getRows();
            		$productIDS = array();
            		foreach ($ret_order_product as $item_product) {
            			$productIDS[] = $item_product['product_id'];
            		}
                        
                    //查询该用户累积消费金额
                    $sql = "select cost from  ".ORDER." where pay_status='2' and status='2' and member_id = ".$memberId."";
                    $this->db->query($sql);
                    $re=$this->db->getRows();
                    foreach($re as $vos){
                        $allCost += $vos['cost'];
                    }
                }
                if(in_array(31679, $productIDS) || in_array(31680, $productIDS) || $allCost >= 1000){
                    $bonusInfos = $this->bonusRuleOfRecomendingShops[$level];
                    
                    if(!empty($bonusInfos)){
                        $sql = "select direct_rec_mid,level from ".TARENTO." where member_id={$memberId}";
                        $this->db->query($sql);
                        $mInfo = $this->db->fetchRow();
                        
                        //查询直接推荐人用户等级，只有红人才有推荐奖
                        $sql = "select direct_rec_mid,level from ".TARENTO." where member_id={$mInfo['direct_rec_mid']}";
                        $this->db->query($sql);
                        $mInfos = $this->db->fetchRow();
                        
                        if(!empty($mInfo)){
                            if($mInfo['direct_rec_mid']>0  && $mInfos['level'] == 2){
                                //直接推荐人
                                $data = array(
                                    'member_id'     =>$mInfo['direct_rec_mid'],
                                    'type'          =>1,
                                    'price'         =>$bonusInfos['direct'],
                                    'p_settle_time' =>date('Y-m-d H:i:s'),
                                    'releranceInfo'  =>array(
                                        'rec_member_id'=>$memberId,
                                        'shop_relation'=>1,
                                        'shop_level'=>$level,
                                    )
                                );
                                $this->insertOneBonusDetail($data,'expand');
                            }
                            
                            $sql = "select direct_rec_mid,level from ".TARENTO." where member_id={$mInfos['direct_rec_mid']}";
                            $this->db->query($sql);
                            $mInfoss = $this->db->fetchRow();
                            
                            if($mInfos['direct_rec_mid']>0 && $mInfoss['level'] == 2){
                                //给上级直接推荐人发红包，且必须是红人
                                $data = array(
                                    'member_id'     =>$mInfos['direct_rec_mid'],
                                    'type'          =>1,
                                    'price'         =>$bonusInfos['indirect'],
                                    'p_settle_time' =>date('Y-m-d H:i:s'),
                                    'releranceInfo'  =>array(
                                        'rec_member_id'=>$memberId,
                                        'shop_relation'=>2,
                                        'shop_level'=>$level,
                                    )
                                );
                                $this->insertOneBonusDetail($data,'expand');
                            }
                    
                            return true;
                        }
                    }
                    
                    
                    
                }else{
                    $bonusInfo = $this->bonusRuleOfRecomendingShop[$level];
                    
                    if(!empty($bonusInfo)){
                        $sql = "select direct_rec_mid,indirect_rec_mid,level from ".TARENTO." where member_id={$memberId}";
                        $this->db->query($sql);
                        $mInfo = $this->db->fetchRow();
                    
                        if(!empty($mInfo)){
                            if($mInfo['direct_rec_mid']>0){
                                //直接推荐人
                                $data = array(
                                    'member_id'     =>$mInfo['direct_rec_mid'],
                                    'type'          =>1,
                                    'price'         =>$bonusInfo['direct'],
                                    'p_settle_time' =>date('Y-m-d H:i:s'),
                                    'releranceInfo'  =>array(
                                        'rec_member_id'=>$memberId,
                                        'shop_relation'=>1,
                                        'shop_level'=>$level,
                                    )
                                );
                                $this->insertOneBonusDetail($data,'expand');
                            }
                    
                            if($mInfo['indirect_rec_mid']>0){
                                //间接推荐人
                                $data = array(
                                    'member_id'     =>$mInfo['indirect_rec_mid'],
                                    'type'          =>1,
                                    'price'         =>$bonusInfo['indirect'],
                                    'p_settle_time' =>date('Y-m-d H:i:s'),
                                    'releranceInfo'  =>array(
                                        'rec_member_id'=>$memberId,
                                        'shop_relation'=>2,
                                        'shop_level'=>$level,
                                    )
                                );
                                $this->insertOneBonusDetail($data,'expand');
                            }
                    
                            return true;
                        }
                    }
                }
                
                
                    
            }
	    }
	    
	    return false;
	}
	
	/**
	 * 写入一个红包
	 * @param unknown $data
	 * @param unknown $type 推广'expand',销售'sales',服务'service',订单任务'task_count',推广任务'task_expand'
	 */
	public function insertOneBonusDetail($data,$type){
	    if(!empty($data) && !empty($type)){
	        //写入红包详情表
	        $bonusStatus = 0;
	        $relation_ms_id = $data['releranceInfo']['rec_member_id'] ? $data['releranceInfo']['rec_member_id'] : 0;
	        $service_ms_id = isset($data['releranceInfo']['service_ms_id']) ? $data['releranceInfo']['service_ms_id'] : 0;
	        if(in_array($type, array('sales','service'))){
	            $bonusStatus = -1;
	        }
	        $sql = "insert into ".MICROSHOPBONUSDETAIL." (`member_id`,`type`,`price`,`p_settle_time`,`status`,`relation_ms_id`) values('{$data['member_id']}','{$data['type']}','{$data['price']}','{$data['p_settle_time']}','{$bonusStatus}','{$relation_ms_id}')";
	        $this->db->query($sql);
	        $bonusId = $this->db->lastid();
	        
	        if($bonusId>0){
	            if($type == 'sales' && $data['releranceInfo']['is_self'] == 0){
	                $orderId = $data['releranceInfo']['order_id'];
	                //给店主推送消息
	                $replaceArr = [
	                    'subject'=>[
	                        '{{titlePre}}'=>'您推广的店铺',
	                        '{{shopName}}'=>$data['releranceInfo']['shop_name']
	                    ],
	                    'message'=>[
	                        '{{bonusDesc}}'=>$data['releranceInfo']['isSelfCostOrder'] ? '补发' : '',
	                        '{{price}}' =>round($data['price'],2)
	                    ]
	                ];
	                //订单商品信息
	                $sql = "select product_name from ".ORPRO." where order_id='{$orderId}' limit 1";
	                $this->db->query($sql);
	                $productName = $this->db->fetchField('product_name');
	                //用户昵称
	                $sql = "select name from ".MEMBER." where userid='{$data['releranceInfo']['order_member_id']}' limit 1";
	                $this->db->query($sql);
	                $userName = $this->db->fetchField('name');
	                
	                $param = [
	                    'memberId'=>$data['member_id'],
	                    'keyword1'=>$this->config['money'].' '.$data['releranceInfo']['order_cost']."（实际参与提成金额:".$this->config['money']." ".round($data['releranceInfo']['order_price'],2)."）",
	                    'keyword2'=>$productName,
	                    'keyword3'=>$orderId,
	                    'keyword4'=>$userName,
	                    'url'=>'http://wx.52ywy.com/?shop='.$data['member_id'].'#&shop/orderdetail/?id='.$orderId
	                ];
	                include_once($this->config["webroot"]."/lib/Helper.php");
	                Helper::pushMessage('shopOrderSuccess', $replaceArr, $param);
	            }
	            if($type == 'expand'){
    	            $shopInfo = $this->get_shop_info($data['member_id']);
//     	            //给用户推送消息
//     	            $replaceArr = [
//     	                'subject'=>[
//     	                    '{{bonusType}}'=>$this->bonusTypeName[$data['type']]
//     	                ],
//     	                'message'=>[
//     	                    '{{shopName}}' =>$shopInfo['name'],
//     	                    '{{shopLevel}}' =>$shopInfo['level']==1?'首席馆':($shopInfo['level']==2?'红人馆':'吃货')
//     	                ]
//     	            ];
//     	            $param = [
//     	                'first'=>$data['member_id'],
//     	                'keyword1'=>$this->config['money'].' '.$data['price'],
//     	                'keyword2'=>$data['p_settle_time'],
//     	                'url'     =>'http://wx.52ywy.com/?shop='.$data['member_id'].'#&shop/generalize/?type='.$data['type']
//     	            ];
//     	            include_once($this->config["webroot"]."/lib/Helper.php");
//     	            Helper::pushMessage('parentOrderSuccess', $replaceArr, $param);
    	            $replaceArr = [];
	                $param = [
    	                'memberId'=>$data['member_id'],
    	                'keyword1'=>$shopInfo['name'],
    	                'keyword2'=>$data['price'] ."元",
    	                'keyword3'=>date("YmdHis"),
    	                'url'     =>'http://wx.52ywy.com/?shop='.$data['member_id'].'#&shop/generalize/?type='.$data['type']
    	            ];
    	            include_once($this->config["webroot"]."/lib/Helper.php");
    	            Helper::pushMessage('tuijianSuccess', $replaceArr, $param);
	            }
	            
	            
    	        //写红包其他相关表
    	        switch ($type)
    	        {
    	            case 'expand':    //推广获得奖励
    	                $sql = "insert into ".MICROSHOPBONUSEXPAND." (`bonus_id`,`rec_member_id`,`shop_relation`,`shop_level`) values('{$bonusId}','{$data['releranceInfo']['rec_member_id']}','{$data['releranceInfo']['shop_relation']}','{$data['releranceInfo']['shop_level']}')";
    	                $this->db->query($sql);
    	                break;
    	            case 'sales':    //销售获得奖励
    	                $sql = "insert into ".MICROSHOPBONUSSALES." (`bonus_id`,`order_id`,`order_price`,`rebate_rate`) values('{$bonusId}','{$data['releranceInfo']['order_id']}','{$data['releranceInfo']['order_price']}','{$data['releranceInfo']['rebate_rate']}')";
    	                $this->db->query($sql);
    	                break;
    	            case 'service':  //服务获得奖励
    	                $sql = "insert into ".MICROSHOPBONUSSERVICE." (`bonus_id`,`order_id`,`order_price`,`rebate_rate`,`service_ms_id`) values('{$bonusId}','{$data['releranceInfo']['order_id']}','{$data['releranceInfo']['order_price']}','{$data['releranceInfo']['rebate_rate']}','{$service_ms_id}')";
    	                $this->db->query($sql);
    	                break;
    	            case 'task_count':
    	                $sql = "insert into ".MICROSHOPBONUSTASKCOUNT." (`bonus_id`,`order_amount`,`rebate`) values('{$bonusId}','{$data['releranceInfo']['order_amount']}','{$data['releranceInfo']['rebate']}')";
    	                $this->db->query($sql);
    	                break;
    	            case 'task_expand':
    	                $sql = "insert into ".MICROSHOPBONUSTASKEXPAND." (`bonus_id`,`expand_shop_number`) values('{$bonusId}','{$data['releranceInfo']['expand_shop_number']}')";
    	                $this->db->query($sql);
    	                break;
                    default:
                        break;
    	        }
    	        
    	        return true;
	        }
	    }
	    
	    return false;
	}

	/**
	 * 计算各类奖励
	 * 根据产品活动类型，以及用户的等级
	 *
	 * @author akiler
	 * @since 20160621
	 * @param $orderInfo
	 * @param $orderProductList
	 * @param $shopLevel
	 * @return array
	 */
	public function calculateKindsOfBonus($orderInfo, $orderProductList, $shopLevel){
		// 如果是第二单，则按照普通区进行分红
		$sql = "SELECT COUNT(id) AS num_fan FROM haiou_quanfan WHERE member_id={$orderInfo['member_id']}";
		$this->db->query($sql);
		$activeOrder = $this->db->fetchRow();

		$data = array();

		// 按照活动类型分组，普通区active_id为0；
		foreach ($orderProductList as $item_product) {
			// 如果已经购买，则都是普通区产品
			if($activeOrder['num_fan'] > 0){
				$item_product['active_id'] = 0;
			}
			$data[$item_product['active_id']][] = $item_product;
		}

		$orderMinus = $orderInfo['cpns_price'] + $orderInfo['discount'] - $orderInfo['ms_discount'];

		$calcData = array();

		// 计算每组的商品消费金额
		foreach ($data as $key_d => $item_d) {
			$calcData[$key_d] = 0;
			foreach ($item_d as $item_d_pro) {
				$calcData[$key_d] += $item_d_pro['price'] * $item_d_pro['num'];
			}
		}

		$numCalc = count($calcData);
		$sumCalc = array_sum($calcData);
		$countCalc = 1;
		$sumRate = 0;

		// 扣除每组中的代金券，打折数据
		foreach ($calcData as $key_calc => $item_calc) {
			if($countCalc < $numCalc){
				// 按比例扣除
				$rate = ceil(($item_calc/$sumCalc) * $orderMinus);
				$calcData[$key_calc] -= $rate;
				$sumRate += $rate;
			}else{
				// 最后一个
				$calcData[$key_calc] -= $orderMinus - $sumRate;
			}

			$countCalc++;
		}

		// 计算各类奖励
		$bonusData = array(
				'own'   		=> 0,
				'hong_shop_1'   => 0,
				'shop_1'        => 0,
				'shop_2'        => 0
		);

		foreach ($calcData as $key_calc => $item_calc) {
			$allRule = $this->bonusRuleOfAll[$key_calc];
			$rule = $this->bonusRuleOfAll[$key_calc][$shopLevel];

			// 如果是吃货以上等级的用户购买，则自己也可以拿分红
			if(floatval($item_calc)<0){
				$item_calc = 1;
			}
			$bonusData['own'] += $item_calc * $rule['self'];

			// 红人购买，首席分红
			$shopLevel == 2 && $bonusData['hong_shop_1'] += $item_calc * ($allRule['1']['self'] - $rule['self']);

			// 吃货购买，红人、首席都能分红
			// 首席分红
			$shopLevel > 2 && $bonusData['shop_1'] += $item_calc * ($allRule['1']['self'] - $allRule['2']['self']);
			// 红人分红
			$shopLevel > 2 && $bonusData['shop_2'] += $item_calc * ($allRule['2']['self'] - $rule['self']);
		}

		return $bonusData;
	}

	public function arr2equation($array, $symbol = ',') {
		if(empty($array) || !is_array($array)) return false;

		$i = 0;
		$count = count($array);
		$equation = '';
		foreach ($array as $key => $value) {
			if ($count == $i) {
				$equation .= $key . '=' . $value;
			} else {
				$equation .= $key . '=' . $value . $symbol;
			}

			$i++;
		}

		return trim($equation, $symbol);
	}

	/**
	 * 微店订单发红包---销售红包
	 * @param unknown $orderId
	 * @param unknown $ignoreStatus 忽略订单状态
	 * @param unknown $selfCost 订单金额，如果传入这个参数则以传入的金额作为返利基数
	 */
	public function giveOutBonusOfOrder($orderId,$ignoreStatus=false,$selfCost=0)
	{
	    $sql = "select member_id,ms_id,cost,cpns_price,discount,ms_discount,status,finished_time from ".ORDER." where order_id={$orderId}";
	    $this->db->query($sql);
	    $orderInfo = $this->db->fetchRow();
	    
	    //查询当前购买产品ID
	    $sql = "select * from ".ORPRO." where order_id = '".$orderId."'";
		$this->db->query($sql);
		$ret_order_product = $this->db->getRows();
		$productIDS = array();
		$productCommonIDS = array();
		$productActiveIDS = array();
// 		$active_id = 0;

		foreach ($ret_order_product as $item_product) {
			$productIDS[] = $item_product['product_id'];

            //TODO::test
// 			$sql="insert into ".ORDERLOG."(order_id,admin_id,admin_name,text,behavior,result) VALUES ('$orderId','','','productId:{$item_product['product_id']}','test ','success')";
// 			$this->db->query($sql);
			
			
// 			if($item_product['active_id'] == 1){
// 				$active_id = 1;
// 				$productActiveIDS[] = $item_product['product_id'];
// 			}else{
// 				$productCommonIDS[] = $item_product['product_id'];
// 			}
		}

		// TODO: test
		$productIDS_json = json_encode($productIDS);
		$sql="insert into ".ORDERLOG."(order_id,admin_id,admin_name,text,behavior,result) VALUES ('$orderId','','','product_id:{$productIDS_json}','test ','success')";
		$this->db->query($sql);
		
	    //查询该用户累积消费金额
	    $sql = "select cost from  ".ORDER." where pay_status='2' and status='2' and member_id = ".$orderInfo['member_id']."";
	    $this->db->query($sql);
	    $re=$this->db->getRows();
	    $allCost = '';
	    foreach($re as $vos){
	        $allCost += $vos['cost'];
	    }
	    //查询当前用户等级
	    $sql = "select level from haiou_tarento where member_id = ".$orderInfo['member_id']."";
	    $this->db->query($sql);
	    $userlevel = $this->db->fetchField('level');
	    
	    if(!empty($orderInfo) && $orderInfo['ms_id']>0){//微店已支付的订单发红包
	        if($orderInfo['status']!=2 && !$ignoreStatus){
	            return false;
	        }
	        $isSelfCostOrder = ($selfCost>0 && $ignoreStatus) ? true : false;//是否是自定义返利基数，补发红包的订单
	        if ($isSelfCostOrder) {
	            $cost = $selfCost;
	        } else {
    	        $cost = $orderInfo['cost'] - $orderInfo['cpns_price'] - $orderInfo['discount'] + $orderInfo['ms_discount'];//参与返利的初始金额
    	        $cost = $cost <= 0 ? 1 : $cost;
	        }
	        
	        $sql = "select a.direct_rec_mid,a.indirect_rec_mid,a.relations,a.level,b.name as shop_name from ".TARENTO." a left join ".MICROSHOP." b on a.member_id=b.member_id where a.member_id={$orderInfo['ms_id']}";
	        $this->db->query($sql);
	        $shopInfo = $this->db->fetchRow();//店铺信息
	        
	        if(!empty($shopInfo)){
	            $shopLevel = $shopInfo['level'] > 3 ? 3 : $shopInfo['level'];
	            $allRule = $this->bonusRuleOfOrder;
	            $rule = $this->bonusRuleOfOrder[$shopLevel];

	            if($userlevel == 3){
	                //如果购买199套餐产品或者累积金额大于1000且该用户身份为吃货.系统则自动升级该吃货为红人馆
	                if(in_array(31679, $productIDS) || in_array(31680, $productIDS) || $allCost >= 1000){
	                    //升级店铺
	                    $this->upgrade_shop($orderInfo['member_id'], 2,$orderId);
	                }
	            }

				// 计算各种奖励，根据购买的产品类型
				$bonusList = $this->calculateKindsOfBonus($orderInfo, $ret_order_product, $shopLevel);
                
// TODO: test
				$bonusListStr = $this->arr2equation($bonusList);
				$sql="insert into ".ORDERLOG."(order_id,admin_id,admin_name,text,behavior,result) VALUES ('$orderId','','','bonusListStr:{$bonusListStr}','test bonus','success')";
				$this->db->query($sql);

	            //给该微店发红包
	            if($shopLevel > 0 && $shopLevel < 3){      //只有红人馆店和首席馆才会产生销售红包
	                $data = array(
	                    'member_id'     =>$orderInfo['ms_id'],
	                    'type'          =>2,
	                    'price'         => $bonusList['own'],
	                    'p_settle_time' =>'',
	                    'releranceInfo'  =>array(
	                        'order_id'=>$orderId,
	                        'order_price'=>$cost,
	                        'rebate_rate'=>$rule['self'],
	                        'shop_name'=>$shopInfo['shop_name'],
	                        'order_member_id'=>$orderInfo['member_id'],
	                        'rec_member_id'     =>$orderInfo['ms_id'],
	                        'is_self'=>1
	                    )
	                );
	                $this->insertOneBonusDetail($data,'sales');
	                
	                //给店主推送消息
	                $replaceArr = [
	                    'subject'=>[
	                        '{{titlePre}}'=>'您的店铺',
	                        '{{shopName}}'=>''
	                    ],
	                    'message'=>[
	                        '{{bonusDesc}}'=>($isSelfCostOrder) ? '补发' : '',
	                            '{{price}}' =>round($data['price'],2)
	                         ]
	                    ];
	                //订单商品信息
	                $sql = "select product_name from ".ORPRO." where order_id='{$orderId}' limit 1";
	                $this->db->query($sql);
    	            $productName = $this->db->fetchField('product_name');
	                    //用户昵称
                    $sql = "select name from ".MEMBER." where userid='{$orderInfo['member_id']}' limit 1";
                    $this->db->query($sql);
                    $userName = $this->db->fetchField('name');
                    $param = [
                    'memberId'=>$orderInfo['ms_id'],
                    'keyword1'=>$this->config['money'].' '.$orderInfo['cost']."（实际参与提成金额:".$this->config['money']." ".round($data['releranceInfo']['order_price'],2)."）",
                    'keyword2'=>$productName,
                    'keyword3'=>$orderId,
                    'keyword4'=>$userName,
                    'url'=>'http://wx.52ywy.com/?shop='.$orderInfo['ms_id'].'#&shop/orderdetail/?id='.$orderId
                    ];
                    include_once($this->config["webroot"]."/lib/Helper.php");
                    Helper::pushMessage('shopOrderSuccess', $replaceArr, $param);
	            }
    	            
	            switch ($shopLevel)
	            {
	                case 1:
	                    if($shopInfo['direct_rec_mid']>0){  //服务奖

	                    }
	                    break;
	                case 2:
	                    $fMid = strstr($shopInfo['relations'],',',true);//上级首席馆的ID

						//给该微店的上级首席馆发红包
						$data = array(
							'member_id'     =>$fMid,
							'type'          =>2,
							'price'         => $bonusList['hong_shop_1'],
							'p_settle_time' =>'',
							'releranceInfo'  =>array(
								'order_id'=>$orderId,
								'order_price'=>$cost,
								'rebate_rate'=>$allRule['1']['self'] - $rule['self'],
								'shop_name'=>$shopInfo['shop_name'],
								'order_member_id'=>$orderInfo['member_id'],
								'rec_member_id'     =>$orderInfo['ms_id'],
								'is_self'=>0,
								'isSelfCostOrder'=>$isSelfCostOrder,
								'order_cost'=>$orderInfo['cost']
							)
						);
						$this->insertOneBonusDetail($data,'sales');

						if($fMid!=$shopInfo['direct_rec_mid']){//如果上级不是他的直接推荐人    服务奖

						}
	                    break;
	                case 3:
	                    $fRate = 0;//首席馆返利比例系数
	                    $fMid = strstr($shopInfo['relations'],',',true);//上级首席馆的ID
	                    $tempRelations = str_replace(','.$fMid.',', '', ','.$shopInfo['relations']);
	                    $sMid = strstr($tempRelations,',',true);//第二级店的ID
	                    
	                    if($sMid == $orderInfo['ms_id']){//如果第二级店就是当前店
// 	                        $fRate = $allRule['1']['self'] - $rule['self'];
	                        $fRate = $allRule['1']['self'] - $allRule['2']['self'];
	                    }else{
    	                    $sql = "select level from ".TARENTO." where member_id={$sMid}";
    	                    $this->db->query($sql);
    	                    $sLevel = $this->db->fetchField('level');

    	                    if($sLevel == 2){
    	                        //给该微店的直接推荐人发红包
    	                       $data = array(
        	                            'member_id'     =>$sMid,
        	                            'type'          =>2,
        	                            'price'         => $bonusList['shop_2'],
        	                            'p_settle_time' =>'',
        	                            'releranceInfo'  =>array(
        	                                'order_id'=>$orderId,
        	                                'order_price'=>$cost,
        	                                'rebate_rate'=>$allRule['2']['self'] - $rule['self'],
        	                                'shop_name'=>$shopInfo['shop_name'],
        	                                'order_member_id'=>$orderInfo['member_id'],
        	                                'rec_member_id'     =>$orderInfo['ms_id'],
        	                                'is_self'=>0,
        	                                'isSelfCostOrder'=>$isSelfCostOrder,
        	                                'order_cost'=>$orderInfo['cost']
        	                            )
        	                        );
    	                        $this->insertOneBonusDetail($data,'sales');
    	                    }
    	                    $fRate = $allRule['1']['self'] - $allRule['2']['self'];
	                    }
	                    
	                    //给该微店的上级首席馆发红包
	                    $data = array(
	                        'member_id'     =>$fMid,
	                        'type'          =>2,
	                        'price'         => $bonusList['shop_1'],
	                        'p_settle_time' =>'',
	                        'releranceInfo'  =>array(
	                            'order_id'=>$orderId,
	                            'order_price'=>$cost,
	                            'rebate_rate'=>$fRate,
	                            'shop_name'=>$shopInfo['shop_name'],
	                            'order_member_id'=>$orderInfo['member_id'],
	                            'rec_member_id'     =>$orderInfo['ms_id'],
	                            'is_self'=>0,
	                            'isSelfCostOrder'=>$isSelfCostOrder,
	                            'order_cost'=>$orderInfo['cost']
	                        )
	                    );

	                    $this->insertOneBonusDetail($data,'sales');

	                    break;
                    default:
                        break;
	            }
	            
	            return true;
	        }
	    }
	    
	    return false;
	}

	/**
	 * 订单完成后使红包可展示，推送消息
	 * @param unknown $orderId
	 */
	public function updateBonusAfterFinishOrder($orderId){
	    $sql = "select ms_id,status,finished_time from ".ORDER." where order_id={$orderId}";
	    $this->db->query($sql);
	    $orderInfo = $this->db->fetchRow();
	    if(!empty($orderInfo) && $orderInfo['ms_id']>0 && $orderInfo['status']==4){
	        $sql = "select level from ".MICROSHOP." where member_id={$orderInfo['ms_id']}";
	        $this->db->query($sql);
	        $shopLevel = $this->db->fetchField('level');//店铺等级
	        
	        $rule = $this->bonusRuleOfOrder[$shopLevel];
	        
	        //查找要更新的红包ID
	        $sql = "select bonus_id from ".MICROSHOPBONUSSALES." where order_id={$orderId}";
	        $this->db->query($sql);
	        $sales = $this->db->getRows();
	        
	        $sql = "select bonus_id from ".MICROSHOPBONUSSERVICE." where order_id={$orderId}";
	        $this->db->query($sql);
	        $service = $this->db->getRows();
	        
	        $bonus = array_merge($sales,$service);
	        $bonusIds = "";
	        foreach ($bonus as $bId)
	        {
	            $bonusIds .= (empty($bonusIds) ? "" : ",").$bId['bonus_id'];
	        }
	        
	        if(!empty($bonusIds)){
	            $p_s_time = date('Y-m-d H:i:s',$orderInfo['finished_time']+$rule['permit_day']*86400);
	            $sql = "update ".MICROSHOPBONUSDETAIL." set status=0,p_settle_time='{$p_s_time}' where id in({$bonusIds}) and status=-1";
	            $this->db->query($sql);
	            
	            $sql = "select * from ".MICROSHOPBONUSDETAIL." where id in({$bonusIds})";
	            $this->db->query($sql);
	            $bonusList = $this->db->getRows();
	            foreach ($bonusList as $v)
	            {
	                //推送消息
	                $this->pushMessageOfOrder($v);
	            }
	        }
	    }
	}
	
	/**
	 * 推送订单红包消息
	 * @param unknown $data
	 */
	public function pushMessageOfOrder($data){
	    $shopInfo = $this->get_shop_info($data['member_id']);
	    //给用户推送消息
	    $replaceArr = [
	        'subject'=>[
	            '{{bonusType}}'=>$this->bonusTypeName[$data['type']]
	        ],
	        'message'=>[
	            '{{shopName}}' =>$shopInfo['name'],
	            '{{shopLevel}}' =>$shopInfo['level']==1?'首席馆':($shopInfo['level']==2?'红人馆':'吃货')
	        ]
	    ];
	    $param = [
	        'memberId'=>$data['member_id'],
	        'keyword1'=>$this->config['money'].' '.$data['price'],
	        'keyword2'=>$data['p_settle_time'],
	        'url'     =>'http://wx.52ywy.com/?shop='.$data['member_id'].'#&shop/generalize/?type='.$data['type']
	    ];
	    include_once($this->config["webroot"]."/lib/Helper.php");
	    Helper::pushMessage('parentOrderSuccess', $replaceArr, $param);
	}
	
	/**
	 * 有支付后的订单更新微店销售额(计算该累计的销售额)
	 * @param unknown $orderId
	 */
	public function updateSalesInfoByOrder($orderId){
	    $sql = "select ms_id,cost,cpns_price,discount,status,order_time,member_id from ".ORDER." where order_id={$orderId}";
	    $this->db->query($sql);
	    $orderInfo = $this->db->fetchRow();
	    if(!empty($orderInfo) && $orderInfo['ms_id']>0 && $orderInfo['status']>1){//微店已支付的订单才统计
	        $cost = $orderInfo['cost'] - $orderInfo['cpns_price'] - $orderInfo['discount'];//参与销售额的金额
	        $flow_time_str = date('Ym',$orderInfo['order_time']);
	        //更新自己
	        $this->saveSalesInfo($orderInfo['ms_id'], $flow_time_str, $cost);
	        
	        $sql = "select relations,level from ".TARENTO." where member_id={$orderInfo['ms_id']}";
	        $this->db->query($sql);
	        $shopInfo = $this->db->fetchRow();
	        $relations = $shopInfo['relations'];
	        
	        if($shopInfo['level']>1){//如果不是顶级则查找所有上级并更新他们的团队销售额
    	        $othersMid = str_replace(','.$orderInfo['ms_id'].',', '', $relations);
    	        if(!empty($othersMid)){
    	            $members = explode(',', $othersMid);
    	            foreach ($members as $memberId)
    	            {
    	                $this->saveSalesInfo($memberId, $flow_time_str, 0, $cost);//更新所有上级的团队销售额
    	            }
    	        }
    	        return true;
	        }
	    }
	    return false;
	}
	
	/**
	 * 更新微店销售额(写入或更新数据)
	 * @param unknown $memberId
	 * @param unknown $flow_time_str
	 * @param number $self_sales
	 * @param number $group_sales
	 */
	private function saveSalesInfo($memberId,$flow_time_str,$self_sales=0,$group_sales=0)
	{
	    $sql = "select id from ".MICROSHOPSALESFLOW." where member_id={$memberId} and flow_time_str='{$flow_time_str}' and status=0";
	    $this->db->query($sql);
	    $flowId = $this->db->fetchField('id');
	    if($flowId>0){//已经有该月的数据则更新
	    	$sql = "update ".MICROSHOPSALESFLOW." set self_sales=self_sales+{$self_sales},group_sales=group_sales+{$group_sales} where id={$flowId}";
	    }else{//无则新增
	        $sql = "insert into ".MICROSHOPSALESFLOW." (`member_id`,`self_sales`,`group_sales`,`flow_time_str`,`status`) values('{$memberId}','{$self_sales}','{$group_sales}','{$flow_time_str}','0')";
	    }
	    $this->db->query($sql);
	    
	    return true;
	}
	
	/**
	 * 结算红人馆月冲单奖
	 * @param string $monthStr
	 */
	public function settleMonthOrderExtraBonus($monthStr=""){
// 	    if($monthStr=='' || $monthStr>=date('Ym')){//不传或传入当前月或比当前月大的值默认为上月
// 	        $monthStr = date('Ym',strtotime('-1 month'));
// 	    }
// 	    //先看该店此月产生的订单中有无支付后取消的订单，有则减掉
// 	    $status = $this->initMicroShopSalesInfo($monthStr);
	    
// 	    if($status){
//     	    $sql = "select a.member_id from ".MICROSHOPSALESFLOW." AS a left join ".MICROSHOP." AS b on a.member_id=b.member_id where a.flow_time_str='{$monthStr}' and a.status=0 and b.level=2 ";
//     	    $this->db->query($sql);
//     	    $shops = $this->db->getRows();
//     	    if(!empty($shops)){
//     	        foreach ($shops as $sv)
//     	        {
//     	            $this->settleMonthOrderExtraBonusOfOneShop($sv['member_id'], $monthStr);
//     	        }
    	        
//     	        return true;
//     	    }
// 	    }
	    
// 	    return false;
	}
	
	/**
	 * 结算一个用户的月冲单奖
	 * @param unknown $memberId
	 * @param unknown $monthStr
	 */
	public function settleMonthOrderExtraBonusOfOneShop($memberId,$monthStr){
	    //开始结算
// 	    $sql = "select self_sales,group_sales from ".MICROSHOPSALESFLOW." where member_id={$memberId} and flow_time_str='{$monthStr}'";
// 	    $this->db->query($sql);
// 	    $salesInfo = $this->db->fetchRow();
// 	    $allSales = $salesInfo['self_sales'] + $salesInfo['group_sales'];
// 	    $rate = $this->get_rebate_rate($allSales);//获取返利比例系数
	    
// 	    $allBackPrice = $allSales*$rate;
	    
// 	    //给第二级的红人馆发红包
// 	    $data = array(
// 	        'member_id'     =>$memberId,
// 	        'type'          =>5,
// 	        'price'         =>$allBackPrice,
// 	        'p_settle_time' =>date('Y-m-d H:i:s'),
// 	        'releranceInfo'  =>array(
// 	            'order_amount'=>$allSales,
// 	            'rec_member_id'=>$memberId,
// 	            'rebate'=>$rate
// 	        )
// 	    );
// 	    $this->insertOneBonusDetail($data,'task_count');
	    
// 	    //标注本月已结算
// 	    $sql = "update ".MICROSHOPSALESFLOW." set status=1 where member_id={$memberId} and flow_time_str='{$monthStr}'";
// 	    $this->db->query($sql);
	    
// 	    return true;
	}
	
	/**
	 * 根据订单情况重新核算微店销售额数据
	 * @param unknown $monthStr
	 */
	public function initMicroShopSalesInfo($monthStr){
	    $sql = "select member_id from ".MICROSHOPSALESFLOW." where flow_time_str='{$monthStr}' and status=0 ";
	    $this->db->query($sql);
	    $shops = $this->db->getRows();
	    if(!empty($shops)){
	        $sTime = strtotime($monthStr.'01');
	        $eTime = strtotime('+1 month',$sTime);
	        foreach ($shops as $sv)
	        {
	            //查找支付后取消订单的总额
	            $sql = "select sum(cost-cpns_price-discount) as total from ".ORDER." where ms_id={$sv['member_id']} and pay_status=2 and status=0 and order_time>'{$sTime}' and order_time<'{$eTime}'";
	            $this->db->query($sql);
	            $price = $this->db->fetchField('total');
	            $price = $price?$price:0;
	            
	            //更新销售额数据
	            if($price>0){
	                //更新本店的销售额
	                $sql = "update ".MICROSHOPSALESFLOW." set self_sales=self_sales-{$price} where member_id={$sv['member_id']} and flow_time_str='{$monthStr}'";
	                $this->db->query($sql);
	                
	                //更新上级的团队销售额
	                $sql = "select relations from ".TARENTO." where member_id={$sv['member_id']}";
	                $this->db->query($sql);
	                $relations = $this->db->fetchField('relations');
	                $bosses = str_replace(','.$sv['member_id'].',', '', ','.$relations);
	                if(!empty($bosses)){
	                    $bosses = trim($bosses,',');
	                    $sql = "update ".MICROSHOPSALESFLOW." set group_sales=group_sales-{$price} where member_id in({$bosses}) and flow_time_str='{$monthStr}'";
	                    $this->db->query($sql);
	                }
	            }
	        }
	         
	        return true;
	    }
	    
	    return false;
	}
	
	/**
	 * 获取返利比例系数
	 * @param unknown $price 销售额
	 * @param unknown $level 店铺等级
	 */
	private function get_rebate_rate($price,$level=2){
	    $rate = 0;
	    foreach ($this->bonusRuleOfMonthSales[$level] as $val)
	    {
	        if($price>=$val['min'] && $price<=$val['max']){
	            $rate = $val['rate'];
	            break;
	        }
	    }
	
	    return $rate;
	}
	
	/**
	 * 领取红包
	 * @param unknown $monthStr
	 * @param unknown $type 红包类型
	 * @param number $memberId
	 */
	public function getBonus($monthStr,$type,$memberId=0){
	    if($memberId>0){//领取某一人的红包
	        $this->getBonusOneMember($memberId, $monthStr, $type);
	        return true;
	    }else{//某一类型红包全部领取
	        $sTime = strtotime($monthStr.'01');
	        $eTime = strtotime('+1 month',$sTime);
	        $sTime = date('Y-m-d',$sTime);
	        $eTime = date('Y-m-d',$eTime);
	        $sql = "select DISTINCT(member_id) from ".MICROSHOPBONUSDETAIL." where type={$type} and status=0 and p_settle_time>='{$sTime}' and p_settle_time<'{$eTime}'";
	        $this->db->query($sql);
	        $memberList = $this->db->getRows();
	        
	        if(!empty($memberList)){
    	        foreach ($memberList as $val)
    	        {
    	            $this->getBonusOneMember($val['member_id'], $monthStr, $type);
    	        }
    	        
    	        return true;
	        }
	    }
	    
	    return false;
	}
	
	/**
	 * 领取某人的红包
	 * @param unknown $memberId
	 * @param unknown $monthStr
	 * @param unknown $type 红包类型
	 */
	public function getBonusOneMember($memberId,$monthStr,$type){
	    $sTime = strtotime($monthStr.'01');
	    $eTime = strtotime('+1 month',$sTime);
	    $sTime = date('Y-m-d',$sTime);
	    $eTime = date('Y-m-d',$eTime);
	    $sql = "select id,price from ".MICROSHOPBONUSDETAIL." where member_id={$memberId} and type={$type} and status=0 and p_settle_time>='{$sTime}' and p_settle_time<'{$eTime}'";
	    $this->db->query($sql);
	    $bonusInfo = $this->db->getRows();
	    if(!empty($bonusInfo)){
	        $price = 0;
	        $bonusIds = "";
	        foreach ($bonusInfo as $val)
	        {
	            $price += $val['price'];
	            $bonusIds .= empty($bonusIds)?$val['id']:",".$val['id'];
	        }
	        
	        $data = array(
	            'member_id'=>$memberId,
	            'type'=>$type,
	            'price'=>$price
	        );
	        $recordsId = $this->insertOneBonusGetRecords($data);
	        
	        if($recordsId>0){//领取成功后更改红包状态
	            $sql = "update ".MICROSHOPBONUSDETAIL." set status=1,record_id={$recordsId},get_time='".date('Y-m-d H:i:s')."' where id in($bonusIds)";
	            $this->db->query($sql);
	            
	            return true;
	        }
	    }
	    
	    return false;
	}
	
	/**
	 * 写入一条红包领取记录
	 * @param unknown $data
	 */
	public function insertOneBonusGetRecords($data){
	    if(!empty($data) && !empty($type)){
	        //写入红包领取记录表
	        $sql = "insert into ".MICROSHOPBONUSGETRECORDS." (`member_id`,`type`,`price`) values('{$data['member_id']}','{$data['type']}','{$data['price']}')";
	        $recordsId = $this->db->query($sql);
	         
	        if($recordsId>0){
	            //更新账户余额
	            include_once($this->config["webroot"]."/module/product/includes/plugin_tarento_class.php");
	            $tarento = new Tarento();
	            $tarento->change_member_account($data['member_id'], $data['price'], 'INCOME_GET_BONUS_'.$data['type'],'后台自动领取红包');
	            
	            return $recordsId;
	        }
	    }
	     
	    return 0;
	}
	
	/**
	 * 写入一条支付日志
	 * @param unknown $data
	 */
	public function insertOnePayLog($data){
	    $memberId = $data['member_id']?$data['member_id']:0;
	    $admin_name = $data['admin_name']?$data['admin_name']:"";
	    $payment_name = $data['payment_name']?$data['payment_name']:"";
	    $text = $data['text']?$data['text']:"";
	    $behavior = $data['behavior']?$data['behavior']:"";
	    $price = $data['price']?$data['price']:0;
	    
	    if($memberId>0){
	        $sql = "insert into ".MICROSHOPPAYLOG." (`member_id`,`admin_name`,`payment_name`,`text`,`behavior`,`price`) values('{$memberId}','{$admin_name}','{$payment_name}','{$text}','{$behavior}','{$price}')";
	        $this->db->query($sql);
	        
	        return true;
	    }
	    
	    return false;
	}
	
	/**
	 * 获取微店配置信息
	 * @param unknown $key
	 * @param string $is_json
	 */
	public function getShopConfig($key,$is_json=false){
	    $res = array();
	    if(!empty($key)){
    	    $sql = "select value,level from ".MICROSHOPCONFIG." where `key`='{$key}' and `status`>0 ";
    	    $this->db->query($sql);
    	    
    	    $result = $this->db->getRows();
    	    
    	    if(!empty($result)){
    	        if($is_json){
        	        foreach ($result as $k=>$v)
        	        {
        	            $v['value'] = json_decode($v['value'],true);
        	            $res[$v['level']] = $v['value'];
        	        }
    	        }else{
    	            $res = $result;
    	        }
    	    }
	    }
	    
	    return $res;
	}
	
	/**
	 * 获取是否需要返红包优惠券
	 * @param unknown $level 开店或升级的等级
	 * @param unknown $haveDiscountPrice 是否享有优惠价字段的值 0，1，2
	 */
	private function canOrNotGiveBonusAndCoupons($level,$haveDiscountPrice)
	{
	    $res = false;
	    if($level==3){
	        $res = true;
	    }else{
	        if($level==2 && $haveDiscountPrice!=1){
	            $res = true;
	        }
	        
	        if($level==1 && $haveDiscountPrice!=2){
	            $res = true;
	        }
	    }
	    
	    return $res;
	}
	
	/**
	 * 把用户的关系绑定到另一人下面
	 * @param unknown $memberId 要更改的用户ID
	 * @param unknown $dMemberId 要绑定到谁的用户ID
	 */
	public function bindMemberToOtherTree($memberId,$dMemberId,&$error=''){
	    if($memberId>0 && $dMemberId>0){
	        //查出要绑定到的人
	        $sql = "select member_id from ".MICROSHOP." where member_id={$dMemberId}";
	        $this->db->query($sql);
	        $dMSId = $this->db->fetchField('member_id');
	        if(!($dMSId>0)){
	            $error = "要绑定到谁的用户没开店！";
	            return false;
	        }
	        $sql = "select relations,level,direct_rec_mid from ".TARENTO." where member_id={$dMemberId}";
	        $this->db->query($sql);
	        $dMInfo = $this->db->fetchRow();
	        $dRelations = $dMInfo['relations'];
	        $dLevel = $dMInfo['level'];
	        $ddirect_rec_mid = $dMInfo['direct_rec_mid'];
	        if(!empty($dRelations)){
	            //查出要更改的用户
	            $sql = "select relations,level,direct_rec_mid from ".TARENTO." where member_id={$memberId}";
    	        $this->db->query($sql);
    	        $mInfo = $this->db->fetchRow();
    	        $relations = $mInfo['relations'];
    	        $level = $mInfo['level'];
    	        $direct_rec_mid = $mInfo['direct_rec_mid'];
    	        
    	        if(empty($relations)){//普通用户
    	            $error = "普通用户不能绑定！";
    	            return false;
    	        }
    	        
    	        if($level==1){
    	            $error = "要更改的用户已经是首席馆，不能绑定！";
    	            return false;
    	        }elseif($level==2){
    	            if($dLevel!=1){
    	                $error = "要更改的红人馆不能绑定到除首席馆以外的店铺下！";
    	                return false;
    	            }
    	        }
    	        
    	        if($direct_rec_mid!=$this->officialMemberId){
    	            $error = "不是官方店直接下级，不能更改关系！";
    	            return false;
    	        }
    	        
    	        if(strpos($relations, ','.$memberId.',')==false){
    	            $error = "要更改的用户关系存在问题，不能绑定！";
    	            return false;
    	        }
    	        $replacePre = str_replace(','.$memberId.',', '', $relations).',';
    	        //开始更新relations和level
    	        if($level==2){
        	        $sql = "update ".TARENTO." set relations=REPLACE(relations,'{$replacePre}','{$dRelations}') where relations like '{$relations}%'";
        	        $this->db->query($sql);
    	        }else{
    	            $newLevel = $dLevel==1?$level-3:$level-$dLevel-1;
    	            $sql = "update ".TARENTO." set relations=REPLACE(relations,'{$replacePre}','{$dRelations}'),level=level-{$newLevel} where relations like '{$relations}%'";
    	            $this->db->query($sql);
    	        }
    	        //更新他的直接和间接推荐人
    	        $sql = "update ".TARENTO." set direct_rec_mid={$dMemberId},indirect_rec_mid={$ddirect_rec_mid} where member_id={$memberId}";
    	        $this->db->query($sql);
    	        
    	        //更新他的直接下一级用户的间接推荐人
    	        $sql = "select relations from ".TARENTO." where member_id={$memberId}";
    	        $this->db->query($sql);
    	        $newRelations = $this->db->fetchField('relations');
    	        
    	        $sql = "update ".TARENTO." set indirect_rec_mid={$dMemberId} where relations like '{$newRelations}_%' and level={$level}+1";
    	        $this->db->query($sql);
    	        
    	        return  true;
	        }
	        $error = "要绑定到谁的用户没开店！";
	        return false;
	    }
	    $error = "用户ID不能为空！";
	    return false;
	}
	
	/**
	 * 获取店铺数量
	 * @param unknown $level
	 */
	public function getShopNum($level){
	    $num = 0;
	    $sql = "select count(*) as num from ".MICROSHOP." where level={$level}";
	    $this->db->query($sql);
	    $num = $this->db->fetchField('num');
	    
	    return $num;
	}
	
	/**
	 * 微店相关人发钱，直接加余额（目前是拼团用）
	 * @param unknown $memberId
	 * @param unknown $selfCost 金额，如果传入这个参数则以传入的金额作为返利基数
	 */
	public function giveOutBonusOfSelfCost($memberId,$selfCost=0,$typeCode="PIN_TUAN",$orderId=0,$desc="")
	{
	    if($memberId>0 && $selfCost>0){
	        $descArr = [
	            'PIN_TUAN' => '拼团成功发放现金',
	            'DEFAULT'  => '自动写入'
	        ];
	        if(empty($desc)){
    	        $desc = isset($descArr[$typeCode]) ? $descArr[$typeCode] : $descArr['DEFAULT'];
	        }
	        $operationStr = $orderId>0 ? "订单号:".$orderId : "";
	        
            $cost = $selfCost;
	         
	        $sql = "select a.direct_rec_mid,a.indirect_rec_mid,a.relations,a.level,a.have_micro_shop,b.name as shop_name from ".TARENTO." a left join ".MICROSHOP." b on a.member_id=b.member_id where a.member_id={$memberId}";
	        $this->db->query($sql);
	        $shopInfo = $this->db->fetchRow();//店铺信息
	         
	        if(!empty($shopInfo) && $shopInfo['relations']!=''){
	            $relationMId = 0;
	            $isSelf = true;
	            if ($shopInfo['have_micro_shop'] == 0) {//如果该用户未开店，则给上级店铺发
	                $isSelf = false;
	                $relationMId = $memberId;
	                $memberId = $shopInfo['direct_rec_mid'];
	                if ($memberId>0) {
	                    $sql = "select a.direct_rec_mid,a.indirect_rec_mid,a.relations,a.level,a.have_micro_shop,b.name as shop_name from ".TARENTO." a left join ".MICROSHOP." b on a.member_id=b.member_id where a.member_id={$memberId}";
	                    $this->db->query($sql);
	                    $shopInfo = $this->db->fetchRow();//店铺信息
	                    if(empty($shopInfo)){
	                        return false;
	                    }
	                } else {
	                    return false;
	                }
	            }
	            
	            //更新账户余额
	            include_once($this->config["webroot"]."/module/product/includes/plugin_tarento_class.php");
	            $tarento = new Tarento();
	             
	            $shopLevel = $shopInfo['level']>3?3:$shopInfo['level'];
	            $allRule = $this->bonusRuleOfOrder;
	            $rule = $this->bonusRuleOfOrder[$shopLevel];
	             
	            //给该微店发红包
	            $data = array(
	                'member_id'     =>$memberId,
	                'price'         =>$cost*$rule['self']
	            );
	            $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$relationMId,$isSelf);
	             
	            switch ($shopLevel)
	            {
// 	                case 1:
// 	                    if($shopInfo['direct_rec_mid']>0){
// 	                        //给该微店的直接推荐人发红包
// 	                        $data = array(
// 	                            'member_id'     =>$shopInfo['direct_rec_mid'],
// 	                            'price'         =>$cost*$rule['direct']
// 	                        );
// 	                        $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
// 	                    }
// 	                    break;
	                case 2:
	                    $fMid = strstr($shopInfo['relations'],',',true);//上级首席馆的ID
	                    $sql = "select direct_rec_mid from ".TARENTO." where member_id={$fMid}";
	                    $this->db->query($sql);
	                    $fdrMid = $this->db->fetchField('direct_rec_mid');//上级首席馆的直接推荐人ID
	
	                    //给该微店的上级首席馆发红包
	                    $data = array(
	                        'member_id'     =>$fMid,
	                        'price'         =>$cost*($allRule['1']['self'] - $rule['self'])
	                    );
	                    $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
	                     
// 	                    if($fdrMid>0){
// 	                        //给该微店的上级首席馆的直接推荐人发红包
// 	                        $data = array(
// 	                            'member_id'     =>$fdrMid,
// 	                            'price'         =>$cost*$allRule['1']['direct']
// 	                        );
// 	                        $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
// 	                    }
	
// 	                    if($fMid!=$shopInfo['direct_rec_mid']){//如果上级不是他的直接推荐人
// 	                        //给该微店的直接推荐人发红包
// 	                        $data = array(
// 	                            'member_id'     =>$shopInfo['direct_rec_mid'],
// 	                            'price'         =>$cost*$rule['direct']
// 	                        );
// 	                        $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
// 	                    }
	                    break;
	                case 3:
	                    $fRate = 0;//首席馆返利比例系数
	                    $fMid = strstr($shopInfo['relations'],',',true);//上级首席馆的ID
	                    $tempRelations = str_replace(','.$fMid.',', '', ','.$shopInfo['relations']);
	                    $sMid = strstr($tempRelations,',',true);//第二级店的ID
	                     
	                    if($sMid == $memberId){//如果第二级店就是当前店
	                        $fRate = $allRule['1']['self'] - $rule['self'];
	                    }else{
	                        $sql = "select level from ".TARENTO." where member_id={$sMid}";
	                        $this->db->query($sql);
	                        $sLevel = $this->db->fetchField('level');
	                         
	                        if($sLevel == 2){//第二级店为红人馆
	                            if($sMid!=$shopInfo['direct_rec_mid']){//如果他的直接推荐人不是第二级的红人馆
	                                //给该微店的直接推荐人发红包
	                                $data = array(
	                                    'member_id'     =>$shopInfo['direct_rec_mid'],
	                                    'price'         =>$cost*$rule['direct']
	                                );
	                                $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
	                                 
	                                //给第二级的红人馆发红包
	                                $data = array(
	                                    'member_id'     =>$sMid,
	                                    'price'         =>$cost*($allRule['2']['self'] - $rule['self'] - $rule['direct'])
	                                );
	                                $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
	                                 
	                            }else{
	                                //给第二级的红人馆发红包
	                                $data = array(
	                                    'member_id'     =>$sMid,
	                                    'price'         =>$cost*($allRule['2']['self'] - $rule['self'])
	                                );
	                                $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
	                                 
	                            }
	                             
// 	                            $sql = "select direct_rec_mid from ".TARENTO." where member_id={$sMid}";
// 	                            $this->db->query($sql);
// 	                            $sdrMid = $this->db->fetchField('direct_rec_mid');//第二级的红人馆的直接推荐人ID
// 	                            if($sdrMid!=$fMid){//如果一级的首席馆不是他的直接推荐人
// 	                                //给该微店的直接推荐人发红包
// 	                                $data = array(
// 	                                    'member_id'     =>$sdrMid,
// 	                                    'price'         =>$cost*$allRule['2']['direct']
// 	                                );
// 	                                $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
// 	                            }
	
	                            $fRate = $allRule['1']['self'] - $allRule['2']['self'];
	                        }else{
	                            //给该微店的直接推荐人发红包
	                            $data = array(
	                                'member_id'     =>$shopInfo['direct_rec_mid'],
	                                'price'         =>$cost*$rule['direct']
	                            );
	                            $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
	                             
	                            $fRate = $allRule['1']['self'] - $rule['self'] - $rule['direct'];
	                        }
	                    }
	                     
	                     
	                    //给该微店的上级首席馆发红包
	                    $data = array(
	                        'member_id'     =>$fMid,
	                        'price'         =>$cost*$fRate
	                    );
	                    $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
	                     
// 	                    $sql = "select direct_rec_mid from ".TARENTO." where member_id={$fMid}";
// 	                    $this->db->query($sql);
// 	                    $fdrMid = $this->db->fetchField('direct_rec_mid');//上级首席馆的直接推荐人ID
// 	                    if($fdrMid>0){
// 	                        //给该微店的上级首席馆的直接推荐人发红包
// 	                        $data = array(
// 	                            'member_id'     =>$fdrMid,
// 	                            'price'         =>$cost*$allRule['1']['direct']
// 	                        );
// 	                        $tarento->change_member_account($data['member_id'], $data['price'], $typeCode,$desc,$operationStr,$memberId);
// 	                    }
	
	                    break;
	                default:
	                    break;
	            }
	             
	            return true;
	        }
	    }
	     
	    return false;
	}
}
?>